package com.example.redpocket.service.impl;

import com.example.redpocket.configuration.redis.RedisLockUtil;
import com.example.redpocket.configuration.redis.RedisUtil;
import com.example.redpocket.controller.RedPacketController;
import com.example.redpocket.dao.RedPacketRepository;
import com.example.redpocket.entity.RedPacket;
import com.example.redpocket.entity.RedPacketRecord;
import com.example.redpocket.entity.Result;
import com.example.redpocket.service.RedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.transaction.Transactional;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
;

@Service
public class RedPacketServiceImpl implements RedPacketService {
    private final static Logger logger = LoggerFactory.getLogger(RedPacketController.class);

    @Autowired
    AmqpTemplate amqpTemplate;
    @Autowired
    RedisLockUtil redisLockUtil;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedPacketRepository redPacketRepository;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public Result startGrab(long redPacketId,String userId) {
        int money=0;
        Boolean res=false;
        try{
            res=redisLockUtil.tryLock(redPacketId+"", TimeUnit.SECONDS,3,10);
            if(res){
                int restPeople= (int) redisUtil.decr(redPacketId+"-num",1);
                if(restPeople<0){
                    logger.info("手慢了，红包已抢完");

                    return Result.error("手慢了，红包已抢完");
                }else {
                    if(restPeople==0){
                        money= (int) redisUtil.get(redPacketId+"-money");
                    }else{

                        int restMoney= (int) redisUtil.get(redPacketId+"-money");
                        money=new Random().nextInt(restMoney/(restPeople+1)*2-1)+1;//restPeople提前减了1，所以要进行加1操作
                        System.out.println("restMoney:"+restMoney+"  restPeopole:"+restPeople+"  money:"+money);
                    }
                    redisUtil.decr(redPacketId+"-money",money);

                    RedPacketRecord redPacketRecord=new RedPacketRecord();
                    redPacketRecord.setCreateTime(new Date());
                    redPacketRecord.setUid(userId);
                    redPacketRecord.setMoney(money);
                    redPacketRecord.setRedPacketId(redPacketId);
                    amqpTemplate.convertAndSend("red_packet_record",redPacketRecord);

                }
            }else{
                logger.info("手慢了....红包已抢完");
                return Result.error("手慢了。。。。红包已抢完");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(res){
                redisLockUtil.unlock(redPacketId+"");
            }
        }
        return Result.ok(money);
    }

    @Override
    public Result saveRedPacket(int totalAmount, int totalPacket) {

        int redPacketId=new Random().nextInt(90)+10;
        redisUtil.set("redPacketId",redPacketId);
        redisUtil.cacheValue(redPacketId+"-num",totalPacket);
        redisUtil.cacheValue(redPacketId+"-money",totalAmount);

        RedPacket redPacket=new RedPacket.Builder()
                .setCreateTime(new Date())
                .setRedPacketId(redPacketId)
                .setTotalAmount(totalAmount)
                .setTotalPacket(totalPacket)
                .build();

        redPacketRepository.save(redPacket);

        return Result.ok(redPacket);
    }
}
